import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

// 消息类型定义
export interface Message {
  id: number;
  type: '系统通知' | '任务提醒' | '项目更新' | '缺陷提醒' | '团队协作' | '需求提醒' | 'Bug提醒';
  title: string;
  content: string;
  time: string;
  read: boolean;
  important?: boolean;
  relatedId?: string;
  relatedType?: 'task' | 'requirement' | 'bug';
}

// 消息Context类型定义
interface MessageContextType {
  // 消息列表
  messages: Message[];
  // 未读消息数量
  unreadCount: number;
  // 添加消息
  addMessage: (message: Omit<Message, 'id' | 'read'>) => void;
  // 标记消息为已读
  markAsRead: (messageId: number) => void;
  // 标记所有消息为已读
  markAllAsRead: () => void;
  // 删除消息
  deleteMessage: (messageId: number) => void;
  // 删除所有已读消息
  deleteAllRead: () => void;
  // 获取消息统计
  getMessageStats: () => {
    total: number;
    unread: number;
    important: number;
  };
  // 根据类型筛选消息
  getMessagesByType: (type: string) => Message[];
  // 根据已读状态筛选消息
  getMessagesByReadStatus: (read: boolean) => Message[];
}

// 创建Context
const MessageContext = createContext<MessageContextType | undefined>(undefined);

// 初始消息数据
const initialMessages: Message[] = [
  {
    id: 1,
    type: '系统通知',
    title: '系统维护通知',
    content: '系统将于今晚23:00-24:00进行例行维护，期间可能无法访问，请提前做好准备。',
    time: '2023-12-06 14:30:00',
    read: false,
    important: true
  },
  {
    id: 2,
    type: '任务提醒',
    title: '任务即将到期',
    content: '您的任务"用户登录功能开发"将于明天到期，请及时处理。',
    time: '2023-12-06 10:15:00',
    read: false,
    important: true,
    relatedId: 'TASK-001',
    relatedType: 'task'
  },
  {
    id: 3,
    type: '项目更新',
    title: '项目进度更新',
    content: '项目"电商系统项目群"已完成80%，请查看最新进度。',
    time: '2023-12-05 16:45:00',
    read: true,
    important: false
  },
  {
    id: 4,
    type: '缺陷提醒',
    title: '新缺陷报告',
    content: '用户反馈登录页面存在样式问题，请及时处理。',
    time: '2023-12-05 14:20:00',
    read: true,
    important: false
  },
  {
    id: 5,
    type: '团队协作',
    title: '新团队成员加入',
    content: '新成员李工程师已加入项目团队，请欢迎新同事。',
    time: '2023-12-04 09:30:00',
    read: true,
    important: false
  },
  {
    id: 6,
    type: '系统通知',
    title: '新功能发布',
    content: '系统新增了消息中心功能，可以更好地管理您的通知消息。',
    time: '2023-12-03 15:00:00',
    read: true,
    important: false
  }
];

// Provider组件
interface MessageProviderProps {
  children: ReactNode;
}

export const MessageProvider: React.FC<MessageProviderProps> = ({ children }) => {
  const [messages, setMessages] = useState<Message[]>(initialMessages);

  // 计算未读消息数量
  const unreadCount = messages.filter(msg => !msg.read).length;

  // 添加消息
  const addMessage = (messageData: Omit<Message, 'id' | 'read'>) => {
    const newMessage: Message = {
      ...messageData,
      id: Date.now(), // 使用时间戳作为ID
      read: false
    };
    
    setMessages(prev => [newMessage, ...prev]);
  };

  // 标记消息为已读
  const markAsRead = (messageId: number) => {
    setMessages(prev => 
      prev.map(msg => 
        msg.id === messageId ? { ...msg, read: true } : msg
      )
    );
  };

  // 标记所有消息为已读
  const markAllAsRead = () => {
    setMessages(prev => 
      prev.map(msg => ({ ...msg, read: true }))
    );
  };

  // 删除消息
  const deleteMessage = (messageId: number) => {
    setMessages(prev => prev.filter(msg => msg.id !== messageId));
  };

  // 删除所有已读消息
  const deleteAllRead = () => {
    setMessages(prev => prev.filter(msg => !msg.read));
  };

  // 获取消息统计
  const getMessageStats = () => ({
    total: messages.length,
    unread: unreadCount,
    important: messages.filter(msg => msg.important).length
  });

  // 根据类型筛选消息
  const getMessagesByType = (type: string) => {
    if (type === 'all') return messages;
    return messages.filter(msg => msg.type === type);
  };

  // 根据已读状态筛选消息
  const getMessagesByReadStatus = (read: boolean) => {
    return messages.filter(msg => msg.read === read);
  };

  // 模拟后端推送消息（用于演示）
  useEffect(() => {
    const interval = setInterval(() => {
      // 30%概率添加新消息
      if (Math.random() < 0.3) {
        const messageTypes: Message['type'][] = ['系统通知', '任务提醒', '项目更新', '缺陷提醒', '团队协作'];
        const randomType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
        const isImportant = Math.random() < 0.2;

        addMessage({
          type: randomType,
          title: `新的${randomType}`,
          content: `这是一条新的${randomType}消息，请及时处理。`,
          time: new Date().toLocaleString('zh-CN'),
          important: isImportant
        });
      }
    }, 30000); // 每30秒检查一次

    return () => clearInterval(interval);
  }, []);

  const value: MessageContextType = {
    messages,
    unreadCount,
    addMessage,
    markAsRead,
    markAllAsRead,
    deleteMessage,
    deleteAllRead,
    getMessageStats,
    getMessagesByType,
    getMessagesByReadStatus
  };

  return (
    <MessageContext.Provider value={value}>
      {children}
    </MessageContext.Provider>
  );
};

// 自定义Hook
// eslint-disable-next-line react-refresh/only-export-components
export const useMessages = () => {
  const context = useContext(MessageContext);
  if (context === undefined) {
    throw new Error('useMessages must be used within a MessageProvider');
  }
  return context;
};

export default MessageContext;